<template>
  <div class="login-form">
    <div class="g-form">
      <div class="g-form-line">
        <span class="g-form-label">用户名:</span>
        <div class="g-form-input">
          <input class="form-input" type="text" v-model="userNameModel" placeholder="请输入用户名"/>
        </div>
        <span class="g-form-error">{{userErrors.errorText}}</span>
      </div>

      <div class="g-form-line">
        <span class="g-form-label">密码:</span>
        <div class="g-form-input">
          <input class="form-input" type="password" v-model="passWordModel" placeholder="请输入密码"/>
        </div>
      </div>

      <div class="g-form-line">
        <div class="g-form-btn">
          <a class="button" @click="onLogin">登录</a>
        </div>
        <span class="g-form-error">{{passwordErrors.errorText}}</span>
      </div>
    </div>
  </div>
</template>

<script>
  export default {
    data() {
      return {
        userNameModel: '',
        passWordModel: '',
        userFlag: false,
        passwordFlag: false
      }
    },
    computed: {
      userErrors() {
        let errorText, status
        if (!/@/g.test(this.userNameModel)) {
          status = false
          errorText = '不包含@'
        } else {
          status = true
          errorText = ''
        }
        if (!this.userFlag) {
          errorText = ''
          this.userFlag = true
        }

        return {
          status,
          errorText
        }
      },
      passwordErrors() {
        let errorText, status
        if (!/^\w{1,6}$/g.test(this.passWordModel)) {
          status = false
          errorText = '密码不是1-6位'
        } else {
          status = true
          errorText = ''
        }
        if (!this.passwordFlag) {
          errorText = ''
          this.passwordFlag = true
        }

        return {
          status,
          errorText
        }
      }
    },
    methods: {
      onLogin() {
        if (this.userErrors.status && this.passwordErrors.status) {
          this.errorText = ''
          this.$http.get('api/login')
            .then((res) => {
              this.$emit('has-login', res.data)
            }, (error) => {
              console.log(error)
            })

        }
        else {

        }
      }
    }
  }
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
  .g-form-error {
    font-size: 10px;
    color: red;
  }

  .g-form-line {
    margin: 10px;
    padding: 0px;
    float: left;
  }

  .g-form-label {
    display: inline-block;
    width: 80px;
  }

  .g-form-input {
    display: inline-block;
  }

  .form-input {
    box-sizing: border-box;
    font-size: 18px;
    height: 2em;
    border-radius: 4px;
    border: 1px solid #c8cccf;
    color: #6a6f77;
    -web-kit-appearance: none;
    -moz-appearance: none;
    display: block;
    outline: 0;
    padding: 0 5px;
    text-decoration: none;
  }

  .button {
    border-radius: 5px;
    margin: 0 auto;
    display: block;
  }
</style>
